package org.jawa.learning.webapp.util;

import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieHelper {
	private HttpServletRequest request;
	private HttpServletResponse response;
	private Map cookiesMap;
	private String cookiesHeader;

	public CookieHelper(HttpServletRequest request, HttpServletResponse response) {
		this.request = request;
		this.response = response;

		this.cookiesHeader = request.getHeader("Cookie");
		Cookie[] cookies = request.getCookies();
		if (cookies == null) {
			this.cookiesMap = Collections.EMPTY_MAP;
		} else {
			this.cookiesMap = new HashMap(cookies.length);
			for (int i = 0; i < cookies.length; i++)
				this.cookiesMap.put(cookies[i].getName(), cookies[i]);
		}
	}

	public Cookie getCookie(String name) {
		return (Cookie) this.cookiesMap.get(name);
	}

	public String getValue(String name) {
		Cookie cookie = getCookie(name);
		if (cookie == null) {
			return null;
		}
		return cookie.getValue();
	}

	public void removeCookie(String name) {
		Cookie cookie = new Cookie(name, null);
		cookie.setMaxAge(0);
		cookie.setPath(this.request.getContextPath());
		this.response.addCookie(cookie);
	}

	public void removeCookie(String name, String path, String domain) {
		Cookie cookie = new Cookie(name, null);
		cookie.setMaxAge(0);
		cookie.setPath(path);
		if (domain != null) {
			cookie.setDomain(domain);
		}
		this.response.addCookie(cookie);
	}

	public void addCookie(String name, String value) {
		Cookie cookie = new Cookie(name, value);
		cookie.setMaxAge(-1);
		cookie.setPath(this.request.getContextPath());
		this.response.addCookie(cookie);
	}

	public String getCookieStrings() {
		StringBuffer sb = new StringBuffer(64 * this.cookiesMap.size());
		for (Iterator iter = this.cookiesMap.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			sb.append(name).append('=').append(this.cookiesMap.get(name)).append("; ");
		}
		return sb.toString();
	}

	public HttpServletRequest getRequest() {
		return this.request;
	}

	public String getCookiesHeader() {
		return this.cookiesHeader;
	}
}
